package com.whpu.controller;

import com.whpu.pojo.User;
import com.whpu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @CrossOrigin
    @RequestMapping("/findAll")
    public String findAll(Model model, @RequestParam(defaultValue = "1") String pageNum, @RequestParam(defaultValue = "3") String pageSize) {
        int page = Integer.valueOf(pageNum);
        page = page > 0 ? page : 1;
        int size = Integer.valueOf(pageSize);
        size = size > 0 ? size : 3;
        List<User> allByRedis = userService.findAllByRedis();
        int totalSize = allByRedis.size();
        int total = totalSize / size + 1;
        page = page <= total ? page : 1;
        model.addAttribute("totalSize",totalSize);
        model.addAttribute("totalPage", total);
        model.addAttribute("pageSize", size);
        model.addAttribute("pageNum", page);

        List<User> users = userService.findAll(page, size);
        model.addAttribute("users", users);
        return "list";
    }

    @RequestMapping("/save")
    public String save(User user) {
        userService.save(user);
        return "redirect:findAll";
    }

}
